package cn.edu.bupt.ch6_2.service.impl;

import cn.edu.bupt.ch6_2.dto.ProductWithComments;
import cn.edu.bupt.ch6_2.entity.Product;
import cn.edu.bupt.ch6_2.mapper.ProductMapper;
import cn.edu.bupt.ch6_2.service.IProductService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class ProductServiceImpl  implements IProductService {
    @Resource
    private  ProductMapper productMapper;

    @Override
    public List<Product> findAll(){
        return productMapper.findAll();
    }

    @Override
    public int create(Product product){
        return  productMapper.create(product);
    }

    @Override
    //unless条件用来演示结果为null时不缓存
    @Cacheable(value = "product",key = "#id",unless="#result ==null")
    public Product findById(Long id){
        return  productMapper.findById(id);
    }

    @Override
    @CacheEvict(value = "product",key = "#product.id")
    public int updateReturnInt(Product product) {
        return productMapper.update(product);
    }

    @Override
    @CachePut(value = "product",key = "#product.id")
    public Product updateReturnProduct(Product product) {
        int res = productMapper.update(product);
        if(res>0){
            return product;
        }
        return null;
    }


    @Override
    @CacheEvict(value = "product",key = "#id")
    public int deleteById(Long id){
        return productMapper.deleteById(id);

    }

    //一对多级联----嵌套Select查询方案示例
    @Override
    //unless表示 执行结果缓存除非结果list的长度大于2，也就是大于2时不缓存
   // @Cacheable(value = "productsWithComments",key = "#name" ,unless = "#result.size() > 2")
    @Cacheable(value = "productsWithComments",key = "#name")
    public List<ProductWithComments> findByNameWithComments(String name){
        return productMapper.findByNameWithComments(name);
    }

    //一对多级联----嵌套 结果映射方案示例
    @Override
    @Cacheable(value = "productsWithComments_v2",key = "#name")
    public List<ProductWithComments> findByNameWithCommentsV2(String name){
        return productMapper.findByNameWithCommentsV2(name);
    }

}
